// pages/index/serviceList/index.js
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    beeperId: '',
    oldServiceData: [],
    // 服务列表
    serviceList: [],
    selectShow: false,
    selectName: '点击选择服务类型',
    selectId: '',
    // 当前分类id
    classifyId: '',

    // 服务分类列表
    classifyList: [],
    classifyShow: false,
    classifyIds: [],
    classifyNams: [],
    // 商户列表
    shopList: [],
    shopShow: false,
    shopIds: [],
    shopNams: [],

    // 服务内容列表
    contentList: []
  },
  // 打开选择服务类型
  onSelectOpen() {
    this.setData({ selectShow: true });
  },
  // 关闭选择服务类型
  onSelectClose() {
    this.setData({ selectShow: false });
  },
  // 打开选择商户
  onShopOpen() {
    this.setData({ shopShow: true });
  },
  // 关闭选择商户
  onShopClose() {
    this.setData({ shopShow: false });
  },
  // 点击服务类型
  onSelectService(event) {
    this.setData({
      selectName: event.detail.name,
      selectId: event.detail.id,
      shopList: [],
      shopIds: [],
      shopNams: [],
      contentList: []
    });
    this.getShopList();
  },
  // 选择商户
  onShopChange(event) {
    this.setData({
      shopIds: event.detail
    });
  },
  // 确认商户
  onShopConfirm() {
    let list = this.data.shopIds;
    let allList = this.data.shopList;
    // 先转成数字
    for (let i = 0; i < list.length; i++) {
      list[i] = Number(list[i]);
    }
    // 通过id过滤出item
    let names = allList
      .filter(item => {
        if (list.some(item2 => item2 == item.id)) {
          return item;
        }
      })
      .map(item => item.name);

    this.setData({
      shopNams: names
    });

    let busIds = this.data.shopIds.toString();
    let params = {
      classifyId: this.data.selectId,
      businessIds: busIds,
      beeperId: this.data.beeperId
    };

    $api.listServerBtn(params).then(res => {
      this.setData({
        contentList: res.data.data
      });
      console.log('根据服务和商户查询出服务内容列表', this.data.contentList);
      this.setData({ shopShow: false });
    });
  },
  timeId: 0,
  timeIdTwo: 0,
  // 输入框绑定
  onInput(e) {
    let list = this.data.contentList;
    let index = e.currentTarget.dataset.id;
    const { value } = e.detail; // 拿到输入框中的值
    // 防抖
    clearTimeout(this.timeId); //清除定时器
    this.timeId = setTimeout(() => {
      list[index].serverNo = value;
      this.setData({
        contentList: list
      });
      console.log(this.data.contentList);
    }, 500);
  },

  //根据服务类型id查询商户列表
  getShopList() {
    let id = this.data.selectId;
    let params = {
      classifyId: id
    };
    $api.listIdNameByClassifyId(params).then(res => {
      let list = res.data.data;
      if (list.length == 0) {
        Toast.fail('当前服务没有商户');
      } else {
        this.setData({
          shopList: list
        });
        console.log('商户列表', this.data.shopList);
      }
    });
  },

  getShopListTwo() {
    let id = this.data.selectId;
    let params = {
      classifyId: id
    };
    $api.listIdNameByClassifyId(params).then(res => {
      let list = res.data.data;
      if (list.length == 0) {
        Toast.fail('当前服务没有商户');
      } else {
        this.setData({
          shopList: list
        });
        console.log('商户列表', this.data.shopList);
        let ids = [];
        let names = [];
        for (let i = 0; i < list.length; i++) {
          ids.push(list[i].id.toString());
          names.push(list[i].name);
        }
        this.setData({
          shopIds: ids,
          shopNams: names
        });
        this.onShopConfirm();
      }
    });
  },

  // 设为默认
  setDefault(e) {
    let list = this.data.contentList;
    // 下标
    let index = e.currentTarget.dataset.id;
    // 当前编号
    if (list[index].serverNo == '') {
      Toast.fail('请先填写编号');
      return;
    }
    // 默认全部重置
    for (let i = 0; i < list.length; i++) {
      list[i].defaultFlag = 0;
    }
    // 设置下标项默认
    list[index].defaultFlag = 1;
    Toast.success('设置成功');
    this.setData({
      contentList: list
    });
  },

  // 提交
  sumbitList() {
    let list = this.data.contentList;
    let defaultFlag = true;
    let reg = /^[1-4]{1,3}$/;
    for (let i = 0; i < list.length; i++) {
      if (list[i].defaultFlag == 1) {
        defaultFlag = false;
      }
      if (list[i].serverNo == '') {
        Toast.fail('请完善内容的编号');
        return;
      }
      if (!reg.test(list[i].serverNo)) {
        Toast.fail('只能输入1,2,3,4组合的1~3位数');
        return;
      }
    }
    if (defaultFlag) {
      Toast.fail('请设置一项为默认');
      return;
    }
    // 判断编号是否有重复
    const ids = list.map(value => value.serverNo);
    const idsSet = new Set(ids);

    let btnParams = this.data.oldServiceData[0].serverBtnParams;
    let beeperBtnId = [];
    for (let i = 0; i < btnParams.length; i++) {
      beeperBtnId.push(btnParams[i].beeperBtnId);
    }
    if (idsSet.size == ids.length) {
      let params = {
        beeperId: Number(this.data.beeperId),
        btnCode: this.data.oldServiceData[0].btnCode,
        serverBtnParams: list,
        beeperBtnIds: beeperBtnId
      };

      $api.updateServerBtn(params).then(res => {
        if (res.data.status == 0) {
          Toast.success('修改成功！');
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1000);
        }
      });
    } else {
      Toast.fail('编号不能重复');
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let id = options.id;

    if (id != undefined) {
      this.setData({
        beeperId: id,
        oldServiceData: app.globalData.oldServiceMsg,
        classifyId: options.cid
      });
      // 当前服务信息
    }
    // 所有服务
    this.getAllService();
    Toast.loading({
      message: '加载中...',
      forbidClick: true
    });
    setTimeout(() => {
      this.setData({
        selectName: this.data.oldServiceData[0].classifyName,
        selectId: this.data.classifyId
      });
      this.getShopListTwo();
    }, 1000);
  },

  // 查询所有服务
  getAllService() {
    let params = {
      classifyId: this.data.classifyId,
      beeperId: this.data.beeperId
    };
    $api.getAllService(params).then(res => {
      this.setData({
        serviceList: res.data.data
      });
    });
  },
  onChange(event) {},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
